package org.bigdata.platform.json;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.EnumSet;
import java.util.Set;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.spi.json.JsonProvider;
import com.jayway.jsonpath.spi.mapper.MappingProvider;

public abstract class BaseJsonFileObject<E> implements IJsonFileObject<E> {

	private E root;
	
	public BaseJsonFileObject() {

		Configuration.setDefaults(new Configuration.Defaults() {
		
			private final JsonProvider provider = getJsonProvider();
			
			@Override
			public Set<Option> options() {
				return EnumSet.noneOf(Option.class);
			}
			
			@Override
			public MappingProvider mappingProvider() {
				return getMappingProvider();
			}
			
			@Override
			public JsonProvider jsonProvider() {
				return this.provider;
			}
		});
	}
	
	protected abstract JsonProvider getJsonProvider();
	
	protected abstract MappingProvider getMappingProvider();
	
	@Override
	public void readFrom(File file) throws Exception {
		readFrom(new FileInputStream(file));
	}

	@Override
	public void writeTo(File file) throws Exception {
		writeTo(new FileOutputStream(file));
	}

	@Override
	public E getRootNode() {
		return this.root;
	}

	@Override
	public void setRootNode(E root) {
		this.root = root;
	}
	
	public E query(String jsonPath) {
		return JsonPath.read(this.root, jsonPath);
	}
	
	
}
